package ua.maxicash.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ua.maxicash.dao.AppDao;
import ua.maxicash.dao.MessageDao;
import ua.maxicash.vo.Message;

import javax.jdo.annotations.Transactional;
import java.util.List;
import java.util.Set;

@Service("messageService")
public class MessageServiceImpl implements MessageService{

	@Autowired
	MessageDao messageDao;
	
	@Autowired
	WorkerService workerService;

	@Autowired
	AppService appService;
	
	@Autowired
	EmployerService employerService;

    @Autowired
    AppDao appDao;
	
	@Override
	public void sendMessage(String sender, String receiver, String subject,
			String text) {
		
		Message message = new Message();
		
		message.setReceiver(appService.getSystemUserByEmail(receiver));
		message.setSender(appService.getSystemUserByEmail(sender));
		message.setSubject(subject);
		message.setText(text);
		message.setTime(System.currentTimeMillis());
		messageDao.saveMessage(message);
		
	}

	@Override
	public List<Message> getAllMessages() {
		
		return messageDao.listMessages();
		
	}

	@Override
	public List<Message> getAllReceivedMessages(String receiversEmail) {
		
		return messageDao.getAllReceivedMessages(receiversEmail);
		
	}

	@Override
	public List<Message> getAllSentMessages(String sendersEmail) {
		
		return messageDao.getAllSentMessages(sendersEmail);
		
	}

    @Override
    public long getCountOfUnreadMessages(String userEmail) {
        return messageDao.getCountOfUnreadMessages(userEmail);
    }

    @Override
    public Message getMessageById(Long idMessage, boolean markAsRead) {
        return messageDao.getMessageById(idMessage, markAsRead);
    }

    @Override
    public void markMessageAsRead(Long idMessage) {
        messageDao.markMessageAsRead(idMessage);
    }

    @Override
    @Transactional
    public Set<Message> getReceivedMessages(String receiversEmail, Long offset, Long amount) {
        return messageDao.getReceivedMessages(appDao.getSystemUserByEmail(receiversEmail).getIdUser(),offset,amount);
    }

    @Override
    @Transactional
    public Set<Message> getSentMessages(String sendersEmail, Long offset, Long amount) {
        return messageDao.getSentMessages(appDao.getSystemUserByEmail(sendersEmail).getIdUser(),offset,amount);
    }

    @Override
    public long getCountOfReceivedMessages(String receiversEmail) {
        return messageDao.getCountOfReceivedMessages(receiversEmail);
    }

    @Override
    public long getCountOfSentMessages(String sendersEmail) {
        return messageDao.getCountOfSentMessages(sendersEmail);
    }

    @Override
    public void saveMessage(Message message) {
        message.setTime(System.currentTimeMillis());
        messageDao.saveMessage(message);
    }
}
